package com.mall.system.controller;

import com.mall.common.result.Result;
import com.mall.system.service.UserRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户角色关联控制器
 */
@Tag(name = "用户角色关联管理")
@Slf4j
@RestController
@RequestMapping("/system/user-roles")
public class UserRoleController {
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Operation(summary = "根据用户ID获取角色ID列表")
    @GetMapping("/user/{userId}")
    public Result<List<Long>> getRoleIdsByUserId(@PathVariable Long userId) {
        try {
            List<Long> roleIds = userRoleService.selectRoleIdsByUserId(userId);
            return Result.success(roleIds);
        } catch (Exception e) {
            log.error("根据用户ID获取角色ID列表异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "根据角色ID获取用户ID列表")
    @GetMapping("/role/{roleId}")
    public Result<List<Long>> getUserIdsByRoleId(@PathVariable Long roleId) {
        try {
            List<Long> userIds = userRoleService.selectUserIdsByRoleId(roleId);
            return Result.success(userIds);
        } catch (Exception e) {
            log.error("根据角色ID获取用户ID列表异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "更新用户角色")
    @PutMapping("/user/{userId}")
    public Result<Boolean> updateUserRole(
            @PathVariable Long userId,
            @RequestBody List<Long> roleIds) {
        try {
            boolean success = userRoleService.updateUserRole(userId, roleIds);
            if (success) {
                return Result.success(true);
            } else {
                return Result.failed("更新用户角色失败");
            }
        } catch (Exception e) {
            log.error("更新用户角色异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "批量更新用户角色")
    @PutMapping("/role/{roleId}")
    public Result<Boolean> batchUpdateUserRole(
            @PathVariable Long roleId,
            @RequestBody List<Long> userIds) {
        try {
            boolean success = userRoleService.batchUpdateUserRole(userIds, roleId);
            if (success) {
                return Result.success(true);
            } else {
                return Result.failed("批量更新用户角色失败");
            }
        } catch (Exception e) {
            log.error("批量更新用户角色异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
}